package com.dj.mingkong.portal.biz.service.system.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dj.mingkong.common.constant.RedisConstants;
import com.dj.mingkong.common.infrastructure.eo.database.system.UserEo;
import com.dj.mingkong.common.infrastructure.eo.database.system.UserVisitEo;
import com.dj.mingkong.common.microservice.UserContext;
import com.dj.mingkong.common.util.AssertUtils;
import com.dj.mingkong.portal.biz.controller.system.vo.request.UserVisitAddVo;
import com.dj.mingkong.portal.biz.controller.system.vo.request.UserVisitCancelVo;
import com.dj.mingkong.portal.biz.controller.system.vo.request.UserVisitQueryVo;
import com.dj.mingkong.portal.biz.controller.system.vo.response.UserVisitVo;
import com.dj.mingkong.portal.biz.core.base.context.UserContextHolder;
import com.dj.mingkong.portal.biz.repository.database.system.UserRepository;
import com.dj.mingkong.portal.biz.repository.database.system.UserVisitRepository;
import com.dj.mingkong.portal.biz.service.system.UserVisitService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.SecureRandom;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * 用户访客服务接口实现
 *
 * @author zenglonghui
 * @date: 2022/8/21 18:35
 */
@Slf4j
@Service("userVisitService")
public class UserVisitServiceImpl implements UserVisitService {
    @Resource
    private UserVisitRepository userVisitRepository;
    @Resource
    private UserRepository userRepository;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private UserContextHolder userContextHolder;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(UserVisitAddVo addVo) {
        final UserEo userEo = userRepository.getById(addVo.getVisitUserId());
        AssertUtils.isNotNull(userEo, "userId invalid");
        //添加人气
        addPopularity(addVo);
        userContextHolder.getCurrentUserOpt().ifPresent(userInfoContext -> {
            final String key = RedisConstants.VISIT_USER
                    .concat(userInfoContext.getId().toString())
                    .concat(RedisConstants.KEY_SPLIT)
                    .concat(addVo.getVisitUserId().toString());
            if (Boolean.FALSE.equals(redisTemplate.hasKey(key))) {
                saveUserVisit(key, userInfoContext.getId(), userEo);
            }
        });
    }

    @Override
    public Page<UserVisitVo> pageByVo(UserVisitQueryVo queryVo) {
        return userVisitRepository.getMapper()
                .listPage(Page.of(queryVo.getPage(), queryVo.getPageSize()), queryVo);
    }

    @Override
    public Page<UserVisitVo> pageSeenByVo(UserVisitQueryVo queryVo) {
        return userVisitRepository.getMapper()
                .listSeenPage(Page.of(queryVo.getPage(), queryVo.getPageSize()), queryVo);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void cancel(UserVisitCancelVo cancelVo) {
        final UserEo userEo = userRepository.getById(cancelVo.getVisitUserId());
        AssertUtils.isNotNull(userEo, "userEo invalid");
        final Optional<UserVisitEo> optional = userVisitRepository
                .oneOptByUserIdAndVisitUserId(UserContext.getUserId(), cancelVo.getVisitUserId());
        optional.ifPresent(userVisitEo -> {
            userVisitRepository.deleteById(userVisitEo.getId());
            userRepository.updateById(userEo.setVisitCount(userEo.getVisitCount() - 1));
        });
    }

    private void saveUserVisit(String key, Long userId, UserEo userEo) {
        final Optional<UserVisitEo> eoOptional = userVisitRepository
                .oneOptByUserIdAndVisitUserId(userId, userEo.getId());
        eoOptional.ifPresentOrElse(userVisitEo -> {
            log.info("更新访客信息 userId:{}, visitUserId:{}", userId, userEo.getId());
            userVisitRepository.updateById(userVisitEo);
            redisTemplate.opsForValue().set(key, RedisConstants.VISIT_USER, 1, TimeUnit.MINUTES);
        }, () -> {
            log.info("保存访客信息 userId:{}, visitUserId:{}", userId, userEo.getId());
            final UserVisitEo visitEo = UserVisitEo.builder().visitUserId(userEo.getId())
                    .userId(userId).build();
            userVisitRepository.save(visitEo);
            redisTemplate.opsForValue().set(key, RedisConstants.VISIT_USER, 1, TimeUnit.MINUTES);
            userRepository.updateById(userEo.setVisitCount(userEo.getVisitCount() + 1));
        });
    }

    private void addPopularity(UserVisitAddVo addVo) {
        final var rand = new SecureRandom();
        final long num = rand.nextLong(10) + 1;
        final Long increment = redisTemplate.boundHashOps(RedisConstants.POPULARITY_USER)
                .increment(addVo.getVisitUserId(), num);
        log.info("添加用户人气 id :{}, 点击数： {}", addVo.getVisitUserId(), increment);
    }
}
